<!doctype html>
<html>
<head>
	<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
	<!-- // <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script> -->
	<script type="text/javascript" src="jquery-2.1.1.js"></script>
	<title>回调函数</title>
</head>
<body>

<ul>
    <li>list item 1</li>
    <li>list item 2</li>
    <li>list item 3</li>
    <li>list item 4</li>
    <li>list item 5</li>
  </ul>
  <p>a paragraph</p>

<script type="text/javascript">



function Callbacks(options) {
  var list = [];
  var self;
  var firingStart;
  var memory;

  function _fire(data) {
    memory = options === 'memory' && data;
    firingIndex =
      firingStart || 0;
    firingStart = 0;
    firingLength = list.length;
    for (; list && firingIndex < firingLength; firingIndex++) {
      if (list[firingIndex](data) === false && options === 'stopOnFalse') {
        break;
      }
    }
  }

  self = {
    add: function(fn) {
      var start = list.length;
      if(options == 'unique'){
          if(-1 ===list.indexOf(fn)){
              list.push(fn)
          }
      }else{
          list.push(fn)
      }
      if (memory) {
        firingStart = start; //获取最后一值
        _fire(memory);
      }
    },
    fire: function(args) {
      if (list) {
        _fire(args)
      }
    }
  }
  return self;
}

function fn1( value ){
    console.log( value );
    return false;
}
 
function fn2( value ){
    fn1( "fn2 says: " + value );
    // return false;
}
 
var callbacks = Callbacks("stopOnFalse");
callbacks.add(fn1);
callbacks.fire("foo");

callbacks.add(fn2);
callbacks.fire("bar");

// callbacks.remove(fn2);
// callbacks.fire("foobar")



// function fn1(val) {
//   console.log('fn1 says ' + val);
// }

// function fn2(val) {
//   console.log('fn2 says ' + val);
// }

// function fn3(val) {
//   console.log('fn3 says ' + val);
// }
// var cbs = Callbacks('memory');

// cbs.add(fn1);
// cbs.fire('foo');

// console.log('..........')
// cbs.add(fn2);

// cbs.fire('bar');

// console.log('..........')
// cbs.add(fn3);
// cbs.fire('aaron');



</script>
</body>
</html>